//
//  RadioListViewController.m
//  FoodList
//
//  Created by Jason on 16/4/12.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "RadioListViewController.h"
#import "RadioListHeaderModel.h"
#import "RadioListSectionTwoCell.h"
#import "RadioListModel.h"
#import "RadioListHeaderView.h"
#import "SectionView.h"
#import "PlayDetailViewController.h"
#import "PlayerManager.h"

@interface RadioListViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *listTableView;
@property (nonatomic, strong) RadioListHeaderModel *headerModel;
@property (nonatomic, strong) NSMutableArray *listModelArray;
@property (nonatomic, strong) RadioListHeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *playArray;

@property (nonatomic, assign) BOOL isUp;

@end

@implementation RadioListViewController

- (NSMutableArray *)listModelArray {
    if (_listModelArray == nil) {
        self.listModelArray = [NSMutableArray array];
    }
    return _listModelArray;
}

- (NSMutableArray *)playArray {
    if (_playArray == nil) {
        self.playArray = [NSMutableArray array];
    }
    return _playArray;
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = YES;
    UIImage *image = [UIImage imageNamed:@"touming.png"];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:image];;
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithTitle:@"<" style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
 //   UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    titleLab.textColor = [UIColor whiteColor];
    titleLab.text = _myTitle;
    self.navigationItem.titleView = titleLab;
    self.navigationItem.leftBarButtonItem = leftBarButton;
    [self requestDataWithMyId:[NSString stringWithFormat:@"%@", _myId] uid:[NSString stringWithFormat:@"%@", _uid]];
    [self creatHeaderView];
    
    self.isUp = NO;
}

- (void)back:(UIBarButtonItem *)button {
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)creatHeaderView {
    self.headerView = [[NSBundle mainBundle] loadNibNamed:@"RadioListHeaderView" owner:nil options:nil].firstObject;
    self.headerView.frame = CGRectMake(0, 0, Width, 170);
    self.headerView.authorImg.layer.masksToBounds = YES;
    self.headerView.authorImg.layer.cornerRadius = 15;
    self.headerView.backgroundImg.layer.masksToBounds = YES;
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    
    UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
    
    effectview.frame = CGRectMake(0, 0, Width, 270);
    
    [self.headerView.backgroundImg addSubview:effectview];
}

- (void)requestDataWithMyId:(NSString *)myId uid:(NSString *)uid {
    NSString *titlrStr = @"%E7%9B%B8%E5%85%B3%E5%BA%A6";
    NSLog(@"%@", [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/album/track?albumId=%@&device=iPhone&pageSize=20&position=1&searchpage=2&source=3&title=%@", myId, titlrStr]);
    [RequestManger requestWithURL:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/album/track?albumId=%@&device=iPhone&pageSize=20&position=1&searchpage=2&source=3&title=%@", myId, titlrStr] requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *albumDic = dataDic[@"album"];
        self.headerModel = [[RadioListHeaderModel alloc] init];
        [_headerModel setValuesForKeysWithDictionary:albumDic];
        _headerView.model = _headerModel;
        NSDictionary *tracksDic = dataDic[@"tracks"];
        NSArray *listArr = tracksDic[@"list"];
        for (NSDictionary *dic in listArr) {
            RadioListModel *model = [[RadioListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.playArray addObject:model.playPathAacv224];
            [self.listModelArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.listTableView.tableHeaderView = _headerView;
            [self.listTableView reloadData];
            
            
      //      [[PlayerManager shardedManager] setMusicArray:_playArray];
        });
    } error:^(NSError *error) {
        NSLog(@"fail");
    }];
}

#pragma mark - tableView代理方法 -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _listModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RadioListSectionTwoCell *sectionTwoCell = [tableView dequeueReusableCellWithIdentifier:@"s2Cell"];
    if (sectionTwoCell == nil) {
        sectionTwoCell = [[NSBundle mainBundle] loadNibNamed:@"RadioListSectionTwoCell" owner:nil options:nil].firstObject;
    }
    sectionTwoCell.listModel = _listModelArray[indexPath.row];
    return sectionTwoCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return Height / 8;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat myAlpha = 1 + scrollView.contentOffset.y / 64;
    if (scrollView.contentOffset.y > -64 && scrollView.contentOffset.y <= 0) {
        [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
        self.navigationController.navigationBar.alpha = myAlpha;
    }else if (scrollView.contentOffset.y > 0) {
        self.navigationController.navigationBar.alpha = 1;
    }else if (scrollView.contentOffset.y == -64) {
        UIImage *image = [UIImage imageNamed:@"touming.png"];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setShadowImage:image];;
        self.navigationController.navigationBar.alpha = 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SectionView *myView = [[NSBundle mainBundle] loadNibNamed:@"SectionView" owner:nil options:nil].firstObject;
    myView.allCount.text = [NSString stringWithFormat:@"共%ld集", _listModelArray.count];
    [myView.paiXuBtn setTitle:@"排序" forState: UIControlStateNormal];
    [myView.paiXuBtn addTarget:self action:@selector(sortListArr:) forControlEvents:UIControlEventTouchUpInside];
    return myView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PlayDetailViewController *playDetailVc = [[PlayDetailViewController alloc] initWithNibName:@"PlayDetailViewController" bundle:[NSBundle mainBundle]];
    
    RadioListModel *model = _listModelArray[indexPath.row];
    playDetailVc.albumId = [NSString stringWithFormat:@"%@", model.albumId];
    playDetailVc.trackId = [NSString stringWithFormat:@"%@", model.trackId];
    playDetailVc.trackUid = [NSString stringWithFormat:@"%@", model.uid];
    
    playDetailVc.index = indexPath.row;
    playDetailVc.modelArray = _listModelArray;
    
    [[PlayerManager shardedManager] setMusicArray:_playArray];
    [[PlayerManager shardedManager] changeMusicWithIndex:indexPath.row];
    
    UINavigationController *playNav = [[UINavigationController alloc] initWithRootViewController:playDetailVc];
    [self presentViewController:playNav animated:YES completion:nil];
}

- (void)sortListArr:(UIButton *)btn {
    if (_isUp) {
        [_listModelArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            NSInteger temp1 = [[obj1 createdAt] integerValue];
            NSInteger temp2 = [[obj2 createdAt] integerValue];
            return temp1 < temp2;
        }];
    }else {
        [_listModelArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            NSInteger temp1 = [[obj1 createdAt] integerValue];
            NSInteger temp2 = [[obj2 createdAt] integerValue];
            return temp1 > temp2;
        }];
    }
    _isUp = !_isUp;
    [self.listTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
